<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { StepStandardModel } from '#/api/process/models';

import { reactive } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { isUndefined } from '@vben/utils';

import { Button, message, Popconfirm } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  createStepStandardApi,
  deleteStepStandardApi,
  getStepStandardListApi,
  updateStepStandardApi,
} from '#/api/process/stepStandard';

import { useDrawerColumns } from '../data';

const state = reactive({
  stepId: 0,
  stepTaskId: 0,
  dataList: [] as StepStandardModel[],
  todoCount: 0,
});

const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const input = drawerApi.getData<Record<string, any>>();
      drawerApi.setState({
        title: `工艺标准设置 [${input.opName}${isUndefined(input.taskName) ? '' : `-${input.taskName}`}]`,
      });

      // 加载数据
      state.stepId = input.stepId;
      state.stepTaskId = input.stepTaskId ?? 0;
      state.todoCount = 0;
      await loadData();
    }
  },
  title: '工艺标准',
  showCancelButton: false,
  showConfirmButton: false,
});

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    columns: useDrawerColumns(),
    data: state.dataList,
    border: true,
    keepSource: true,
    stripe: true,
    editConfig: {
      mode: 'row',
      trigger: 'manual',
      showStatus: true,
      autoClear: false,
    },
    pagerConfig: {
      enabled: false,
    },
  } as VxeTableGridOptions,
});

/**
 * 加载数据
 */
async function loadData() {
  state.dataList.length = 0; // 清空数组
  const data = await getStepStandardListApi(state.stepId, state.stepTaskId);
  state.dataList.push(...data);
}

/**
 * 添加行
 */
function onCreate() {
  // 校验是否有为进行保存的行
  if (state.todoCount > 0) {
    message.warning(`请先保存当前新增的行`);
    return;
  }

  ++state.todoCount;
  const item: StepStandardModel = {
    id: 0,
    stepId: state.stepId,
    stepTaskId: state.stepTaskId,
    parameterName: '',
    parameterCode: '',
    standardValue: '',
    tolerance: '',
    minLimit: null,
    maxLimit: null,
    measurementUnit: '',
    conversion: null,
    digits: null,
    inspectionMethod: '',
  };
  // gridApi.grid.insertAt(item, -1);
  state.dataList.push(item);
  gridApi.grid.setEditRow(item);
}

/**
 * 取消编辑
 */
function onCancel(row: StepStandardModel) {
  gridApi.grid.clearEdit();
  // 恢复到初始状态
  // bug: 更改数据提交保存后，再取消时数据回滚到了最初始状态
  gridApi.grid.revertData(row);
}

/**
 * 编辑保存
 */
async function onSave(row: StepStandardModel) {
  await gridApi.grid?.clearEdit();
  if (await gridApi.grid.validate(row)) {
    message.success(`校验不通过！`);
    return;
  }

  // 更新
  if (row.id > 0) {
    const ok = await updateStepStandardApi(row.id, row);
    if (ok) {
      message.success(`更新成功`);
    }
    return;
  }

  // 新增
  gridApi.setLoading(true);
  const ok2 = await createStepStandardApi(row);
  if (ok2) {
    message.success(`新增成功`);
    await loadData();
    --state.todoCount;
  }
  gridApi.setLoading(false);
}

/**
 * 删除行
 */
async function onDelete(row: StepStandardModel) {
  if (row.id > 0) {
    if (await deleteStepStandardApi(row.id)) {
      message.success(`删除成功`);
      await loadData();
    }
  } else {
    // 直接删除
    state.dataList.splice(
      state.dataList.findIndex((item) => item.id === row.id),
      1,
    );
    --state.todoCount;
  }
}
</script>

<template>
  <Drawer>
    <div class="h-full">
      <Grid>
        <template #toolbar-actions>
          <Button size="small" @click="onCreate()">新增</Button>
        </template>
        <template #action="{ row }">
          <template v-if="gridApi.grid.isEditByRow(row)">
            <Button size="small" type="link" @click="onSave(row)">
              保存
            </Button>
            <Button size="small" type="link" @click="onCancel(row)">
              取消
            </Button>
          </template>
          <template v-else>
            <Button
              size="small"
              type="link"
              @click="gridApi.grid.setEditRow(row)"
            >
              编辑
            </Button>
          </template>
          <Popconfirm title="确定要删除吗？" @confirm="onDelete(row)">
            <Button danger size="small" type="link"> 删除 </Button>
          </Popconfirm>
        </template>
      </Grid>
    </div>
  </Drawer>
</template>
